package com.qfedu.scode.filter;

import com.qfedu.scode.config.RedisKeyConfig;
import com.qfedu.scode.config.SystemConfig;
import com.qfedu.scode.util.RedissonUtil;
import com.qfedu.scode.util.StringUtil;
import com.qfedu.scode.vo.R;
import org.json.JSONObject;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: StartCoding
 * @description: 自动更新Redis中令牌的有效期 &校验令牌
 * @author: Feri(邢朋辉)
 * @create: 2021-01-09 10:38
 */
@Component
@WebFilter("/*")
public class TokenTimeFilter implements Filter {
    private String[] urls={"api/user/save.do","api/user/login.do","all.do"};
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        //获取访问的接口路径
        String url=request.getServletPath();
        System.out.println(url);
        if(url.endsWith(".do")){
            if(index(url)>0){
                //放行 不需要传递令牌
                filterChain.doFilter(request,servletResponse);
            }else {
                //获取令牌
                String token=request.getHeader(SystemConfig.TOKEN_HEADER);
                //校验是否有令牌
                if(StringUtil.isNoEmpty(token)){
                    //验证令牌是否有效
                    String key= RedisKeyConfig.LOGIN_TOKEN+token;
                    if(RedissonUtil.isHave(key)){
                        //存在 令牌有效
                        //更新时间
                        RedissonUtil.expire(key,RedisKeyConfig.LOGIN_TOKEN_TIMES);
                        //放行
                        filterChain.doFilter(request,servletResponse);
                    }else {
                        HttpServletResponse response=(HttpServletResponse) servletResponse;
                        response.setContentType("application/json;charset=UTF-8");
                        response.getWriter().print(new JSONObject(R.fail("亲，令牌无效")).toString());
                    }
                }else {
                    HttpServletResponse response=(HttpServletResponse) servletResponse;
                    response.setContentType("application/json;charset=UTF-8");
                    response.getWriter().print(new JSONObject(R.fail("亲，请传递令牌")).toString());
                }
            }
        }else {
            filterChain.doFilter(request,servletResponse);
        }
    }
    //数组的查询 验证当前的请求路径是否需要拦截处理
    private int index(String u){
        for(String s:urls){
            if(u.endsWith(s)){
                return 1;
            }
        }
        return -1;
    }
}
